<!--协议合同-->
<template>
	<div class="renter-sign-dialog">
		<a-form ref="form" :model="entity" layout="vertical" :rules="renterContractRules(entity)">
			<a-typography-paragraph strong>
				<blockquote>合同类型</blockquote>
			</a-typography-paragraph>
			<a-radio-group v-model:value="entity.contractMedium" class="custom-radio-group" @change="onContractMediumChange">
				<a-space :size="12">
					<template v-for="item in contractTypes" :key="item.type">
						<a-radio-button :value="item.type" :disabled="item.type === 2 && !templates.length">
							<a-typography-paragraph>
								{{ item.title }}
								<small v-if="item.subTitle" v-color="{color: '#86909C'}">（{{ item.subTitle }}）</small>
							</a-typography-paragraph>
							<a-typography-paragraph v-color="{color: '#86909C'}">
								<small>{{ item.desc }}</small>
							</a-typography-paragraph>
							<a-form-item v-if="item.type === 2" name="econtractModelId" class="template-select-wrapper">
								<template #extra v-if="!templates.length && entity.houseId">请前往【企业>电子签约>合同模板】添加</template>
								<a-select
									v-model:value="entity.econtractModelId"
									v-bind="templateOption"
									:disabled="entity.contractMedium === 1"
									@click.prevent>
									<template #notFoundContent>
										<a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE">
											<template #description>
												暂无电子合同模板
												<br />
												请前往【企业>电子签约>合同模板】添加
											</template>
										</a-empty>
									</template>
								</a-select>
							</a-form-item>
						</a-radio-button>
					</template>
				</a-space>
			</a-radio-group>
			<a-typography-paragraph strong>
				<blockquote>企业信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="8">
					<a-form-item label="企业名称：" name="enterPriseId">
						<a-select
							:disabled="props.id !== ''"
							v-model:value="entity.enterPriseId"
							placeholder="请选择企业"
							:options="options.enterpriseList"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="{label: 'enterPriseName', value: 'id'}"
							@change="selectEnterPriseId" />
					</a-form-item>
				</a-col>
				<template v-if="entity.enterPriseId">
					<a-col :span="8">
						<a-form-item label="统一社会信用代码：">
							<a-input v-model:value="entity.societyCode" disabled placeholder="请输入社会信用代码" style="flex: 1" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="联系人信息：">
							<a-input disabled :placeholder="entity.linkmanName + '/' + entity.linkmanPhone" style="flex: 1" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="合作周期：" name="enterPriseTeamWorkId">
							<a-select
								:disabled="props.id !== ''"
								v-model:value="entity.enterPriseTeamWorkId"
								placeholder="请选择合作周期"
								:options="options.teamWork"
								:field-names="{label: 'period', value: 'id'}"
								@change="selectWorkId" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="租金协议价：" name="enterPriseTeamworkDiscountId">
							<a-select
								:disabled="props.id !== ''"
								v-model:value="entity.enterPriseTeamworkDiscountId"
								placeholder="请选择租金协议价"
								:options="options.discount"
								:field-names="{label: 'name', value: 'id'}"
								@change="selectDiscountId" />
						</a-form-item>
					</a-col>
				</template>
			</a-row>

			<a-typography-paragraph strong>
				<blockquote>房间信息</blockquote>
			</a-typography-paragraph>
			<a-form-item name="houseId">
				<a-select
					:disabled="!!contract.houseId || [2, 3, 4].includes(contract.signType)"
					v-model:value="entity.houseId"
					v-bind="searchOption">
					<template v-if="loadings.search" #notFoundContent>
						<a-spin spinning tip="正在搜索，请稍候……" />
					</template>
				</a-select>
			</a-form-item>
			<a-typography-paragraph strong>
				<blockquote>
					承租人信息 (
					<span>
						承租人只能为员工库里的员工,
						<a>去添加</a>
					</span>
					)
				</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="6">
					<a-form-item label="姓名：" :name="['renterInfo', 'name']">
						<a-input-group compact class="display-flex">
							<a-input
								v-model:value="entity.renterInfo.name"
								:disabled="renterDisabled"
								placeholder="请输入姓名"
								style="flex: 1" />
							<a-form-item-rest>
								<a-radio-group v-model:value="entity.renterInfo.gender" button-style="solid">
									<a-radio-button :value="1">男</a-radio-button>
									<a-radio-button :value="2">女</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="手机号：" :name="['renterInfo', 'phone']">
						<a-input
							v-model:value.trim="entity.renterInfo.phone"
							:disabled="renterDisabled"
							:maxlength="11"
							placeholder="请输入手机号" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="身份信息：" :name="['renterInfo', 'identityCard']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.certificationType"
									:options="options.certificateTypes"
									:disabled="entity.contractMedium === 2"
									@change="form.clearValidate([['renterInfo', 'identityCard']])"
									style="width: 120px" />
							</a-form-item-rest>
							<a-input
								v-model:value.trim="entity.renterInfo.identityCard"
								:maxlength="18"
								placeholder="请输入证件号码"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item
						label="证件照片："
						:name="['renterInfo', 'frontImgUrl']"
						:rules="[{required: entity.renterInfo?.needPhoto, message: '请补充证件照片'}]">
						<a-button type="primary" block @click=";(visibles.certificate = true), (renter = entity.renterInfo)">
							<template v-if="entity.renterInfo.frontImgUrl || entity.renterInfo.rearImgUrl">
								<check-outlined />
							</template>
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="客户来源：">
						<a-select
							v-model:value="entity.renterInfo.customerResource"
							placeholder="请选择客户来源"
							:options="options.sources"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收付款账号：">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.paymentType"
									:options="paymentAccountList"
									placeholder="请选择类型"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input
								v-model:value.trim="entity.renterInfo.paymentNo"
								placeholder="请输入账号"
								:maxlength="30"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="紧急联系人：" :name="['renterInfo', 'emergencyName']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.emergencyType"
									:options="relationshipList"
									placeholder="关系"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input v-model:value="entity.renterInfo.emergencyName" placeholder="请输入联系人姓名" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="紧急联系人手机号：" :name="['renterInfo', 'emergencyPhone']">
						<a-input-group compact>
							<a-input
								v-model:value.trim="entity.renterInfo.emergencyPhone"
								:maxlength="11"
								placeholder="请输入联系人手机号" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="职业：">
						<a-select
							v-model:value="entity.renterInfo.profession"
							placeholder="请选择职业"
							:options="occupation"
							allow-clear
							show-search />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="工作单位：">
						<a-input v-model:value.trim="entity.renterInfo.employer" placeholder="请输入工作单位" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="重点人群：">
						<a-select
							v-model:value="entity.renterInfo.keyGroupsType"
							placeholder="请选择重点人群"
							:options="options.keyGroups"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="爱好：">
						<a-tooltip :title="hobbies.join('，') || '请选择爱好'" destroy-tooltip-on-hide>
							<a-select
								v-model:value="entity.renterInfo.interest"
								placeholder="请选择爱好"
								mode="multiple"
								:options="options.hobbies"
								allow-clear
								show-search
								max-tag-count="responsive"
								option-filter-prop="name"
								:field-names="DEFAULT_FIELD_NAME" />
						</a-tooltip>
					</a-form-item>
				</a-col>
			</a-row>
			<a-typography-paragraph strong>
				<blockquote>
					同住人
					<a @click="onClickToAddTogether">
						<plus-circle-filled />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-form-item v-if="entity.renterInfo?.togetherList.length" :name="['renterInfo', 'togetherList']">
				<!--实现表单校验失败滚动到此处-->
				<a-input :bordered="false" style="position: absolute" />
				<a-form-item-rest>
					<vxe-table ref="togetherTable" :data="entity.renterInfo.togetherList" v-bind="togetherTableOption">
						<vxe-column min-width="120px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								姓名
							</template>
							<template #default="{row, rowIndex}">
								<a-input v-model:value="row.name" :bordered="false" placeholder="请输入姓名" />
							</template>
						</vxe-column>
						<vxe-column min-width="120px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								手机号
							</template>
							<template #default="{row, rowIndex}">
								<a-input v-model:value.trim="row.phone" :bordered="false" placeholder="请输入手机号" />
							</template>
						</vxe-column>
						<vxe-column width="140px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								性别
							</template>
							<template #default="{row, rowIndex}">
								<a-radio-group v-model:value="row.gender">
									<a-radio :value="1">男</a-radio>
									<a-radio :value="2">女</a-radio>
								</a-radio-group>
							</template>
						</vxe-column>
						<vxe-colgroup align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								证件信息
							</template>
							<vxe-column width="120px" align="center" header-class-name="display-none">
								<template #default="{row, rowIndex}">
									<a-select v-model:value="row.certificationType" :bordered="false" :options="options.certificateTypes" />
								</template>
							</vxe-column>
							<vxe-column min-width="180px" align="center" header-class-name="display-none">
								<template #default="{row, rowIndex}">
									<a-input v-model:value.trim="row.identityCard" :bordered="false" placeholder="请输入证件号" />
								</template>
							</vxe-column>
						</vxe-colgroup>
						<vxe-column width="120px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								关系
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.renterRelation"
									:bordered="false"
									:options="renterRelationList"
									placeholder="请选择关系" />
							</template>
						</vxe-column>
						<vxe-column title="证件" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a @click=";(visibles.certificate = true), (renter = row)">
									<template v-if="row.frontImgUrl || row.rearImgUrl">
										<check-outlined />
									</template>
									<plus-outlined v-else />
								</a>
							</template>
						</vxe-column>
						<vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a v-color="{color: 'danger'}" @click="onClickToRemoveRow(rowIndex, togetherTable)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
			</a-form-item>
			<a-typography-paragraph v-else style="margin-bottom: 2em" />
			<a-typography-paragraph strong>
				<blockquote>合同信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="6">
					<a-form-item label="成交方式/合同编号：" name="contractNo">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select v-model:value="entity.signType" disabled :options="signTypeList" style="width: 80px" />
							</a-form-item-rest>
							<a-input v-model:value.trim="entity.contractNo" placeholder="请输入合同编号" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item name="beginTime">
						<template #label>
							<div class="display-flex">
								<span style="flex: 1">合同周期：</span>
								<span v-if="entity.beginTime && entity.endTime" style="width: 170px">{{ cycleTip }}</span>
							</div>
						</template>
						<a-input-group compact class="display-flex">
							<a-range-picker
								:value="[entity.beginTime, entity.endTime]"
								:value-format="DATE_FORMAT.DATE"
								:disabled="[[2, 3, 4].includes(contract.signType)]"
								:disabled-date="disabledDate"
								style="flex: 1"
								@change="onDateChange" />
							<a-form-item-rest>
								<a-radio-group
									class="month-quick-radio-group"
									v-model:value="entity.leasePeriod"
									button-style="solid"
									@change="quickSelectDate">
									<a-radio-button :value="1">1月</a-radio-button>
									<a-radio-button :value="3">3月</a-radio-button>
									<a-radio-button :value="6">6月</a-radio-button>
									<a-radio-button :value="12">1年</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="付款方式：">
						<a-input-group compact class="display-flex">
							<a-select
								v-model:value="entity.depositMonth"
								:options="mortgageMonthList"
								placeholder="请选择"
								style="flex: 1" />
							<a-select v-model:value="entity.periodMonth" :options="periodMonthList" placeholder="请选择" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="月租金：" name="price">
						<a-input-number v-model:value="entity.price" :min="0" :precision="2" placeholder="请输入租金" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="押金：" name="deposit">
						<a-input-number v-model:value="entity.deposit" :min="0" :precision="2" placeholder="请输入押金" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收租日设置：" name="payPatternValue">
						<a-input-group compact class="display-flex">
							<template v-if="entity.payPattern == 1">
								<a-input-number
									v-model:value="entity.payPatternValue"
									prefix="提前"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<template v-else>
								<a-input-number
									v-model:value="entity.payPatternValue"
									prefix="固定"
									:min="1"
									:max="31"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<a-form-item-rest>
								<a-select
									v-model:value="entity.payPattern"
									:options="paymentMethodList"
									style="width: 200px"
									@change="entity.payPatternValue = null" />
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="账单生成规则：">
						<a-select v-model:value="entity.cycleType" :options="waningMoonList" placeholder="请选择账单生成规则" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="合同附件：">
						<a-button type="primary" block @click="visibles.attachment = true">
							<check-outlined v-if="entity.attachmentIds?.length" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="物业交割单：">
						<a-button type="primary" block :disabled="!entity.houseId" @click="visibles.delivery = true">
							<check-outlined v-if="delivery" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<!-- <a-col :span="24">
					<a-form-item label="补充说明：" name="addExplanation">
						<a-textarea v-model:value.trim="entity.addExplanation" placeholder="请输入补充说明" :rows="4" show-count :maxlength="200" />
					</a-form-item>
				</a-col> -->
			</a-row>
			<!-- <a-typography-paragraph strong>
				<blockquote>优惠活动</blockquote>
			</a-typography-paragraph> -->
			<a-row>
				<!-- <a-col :span="24">
					<a-form-item label="可以使用活动：">
						<two-columns-select v-model:value="entity.activity"></two-columns-select>
					</a-form-item>
				</a-col>
				<br /> -->
				<a-col :span="24">
					<a-form-item label="补充说明：" name="addExplanation">
						<a-textarea
							v-model:value.trim="entity.addExplanation"
							placeholder="请输入补充说明"
							:rows="4"
							show-count
							:maxlength="200" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-typography-paragraph strong>
				<blockquote>
					加收费用
					<a @click="onClickToAddOtherBill">
						<plus-circle-filled />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-form-item v-if="entity.otherExpenses?.length" name="otherExpenses">
				<a-form-item-rest>
					<vxe-table ref="otherBillTable" :data="entity.otherExpenses" v-bind="otherBillTableOption">
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								费用科目
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.feeSubjectId"
									:bordered="false"
									:options="options.feeSubjects"
									@change="(value: string) => feeSubjectChange(value, row)"
									show-search
									option-filter-prop="name"
									:field-names="{label: 'name', value: 'id', options: 'metaList'}"
									placeholder="请选择费用科目" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								付款方式
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.periodMonth"
									:disabled="row.disabled"
									:bordered="false"
									:options="periodMonthOptions"
									placeholder="请选择付款方式" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								金额
							</template>
							<template #default="{row, rowIndex}">
								<a-input-number
									v-model:value="row.price"
									:bordered="false"
									:controls="false"
									:min="0"
									:precision="2"
									placeholder="请输入金额" />
							</template>
						</vxe-column>
						<vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a v-color="{color: 'danger'}" @click="onClickToRemoveRow(rowIndex, otherBillTable)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
				<!--实现表单校验失败滚动到此处-->
				<a-input disabled :bordered="false" style="position: absolute" />
			</a-form-item>

			<a-typography-paragraph v-else style="margin-bottom: 2em" />
			<a-typography-paragraph strong>
				<blockquote>签约信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="8">
					<a-form-item label="签约人/维护人" name="signEmpId">
						<dept-emp-select
							v-model:dept-id="entity.signDeptId"
							v-model:emp-id="entity.signEmpId"
							@change="form.validate('signEmpId')" />
					</a-form-item>
				</a-col>
				<!-- <a-col :span="8">
					<a-form-item label="维护人：" name="maintainerId">
						<dept-emp-select v-model:emp-id="entity.maintainerId" disabled only-dept placeholder="请选择房源" />
					</a-form-item>
				</a-col> -->
				<a-col :span="8">
					<a-form-item label="签约时间：" name="signTime">
						<a-date-picker v-model:value="entity.signTime" placeholder="请选择签约日期" :value-format="DATE_FORMAT.DATE" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<teleport v-if="visibles.footer" to=".signing-dialog .ant-modal-footer">
			<a-button type="primary" :disabled="disables.save" :loading="loadings.save" @click="submit">保存并核对账单</a-button>
		</teleport>

		<!-- 附件上传 -->
		<file-upload-dialog v-model:visible="visibles.attachment" v-model:files="attachments" />
		<!-- 证件上传 -->
		<certificate-upload-dialog v-model:visible="visibles.certificate" :imgs="renter" />
		<!-- 账单预览 -->
		<renter-bill-preview-dialog v-model:visible="visibles.billPreview" :contract="entity" @success="onSubmitSuccess" />
		<!-- 物业交割单 -->
		<delivery-note
			v-model:visible="visibles.delivery"
			:id="entity.houseId"
			:contractId="contractId"
			@success="data => (delivery = data)" />

		<!-- 通行授权弹窗 -->
		<access-authorization-dialog
			v-model:visible="visibles.accessAuth"
			:device-detail="deviceDetail"
			:hydropower="isShowHydropower"
			@success="updateClancel" />
	</div>
</template>

<script lang="ts" setup>
	import dayjs, {Dayjs} from 'dayjs'
	import {useStore} from '@/store'
	import XEUtils from 'xe-utils'
	import houseApi from '@/api/house-api'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {computed, createVNode, reactive, ref, toRaw, toRef, watch, watchEffect, onMounted, FunctionalComponent, h, render} from 'vue'
	import {
		mortgageMonthList,
		occupation,
		paymentAccountList,
		paymentMethodList,
		periodMonthList,
		periodMonthOptions,
		relationshipList,
		renterRelationList,
		signTypeList,
		waningMoonList
	} from '@/utils'
	import {CheckOutlined, PlusCircleFilled, PlusOutlined, QuestionCircleOutlined} from '@ant-design/icons-vue'
	import CertificateUploadDialog from '@/components/common/certificate-upload-dialog.vue'
	import {Img} from 'yuxin-base/src/types'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'
	import {DEFAULT_FIELD_NAME, DIC_LABEL_MAP, DIC_PID_MAP} from 'yuxin-base/src/constant'
	import {VxeTableInstance, VxeTableProps} from 'vxe-table'
	import {Empty, FormInstance, message, Modal} from 'ant-design-vue'
	import {HouseDetail} from '@/interface/house'
	import {renterContractRules} from '@/rules/contract'
	import DeliveryNote from '@/components/contract/add-tenant-contract-dialog/delivery-note.vue'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import {
		getContractTemplate,
		getCurEleAndWaterQuantity,
		getRenterContractDetail,
		houseDeliveryBatchSave,
		renterContractDeviceDetail,
		getEnterPriseLibraryListAll
	} from '@/api/contract'
	import RenterBillPreviewDialog from '@/components/contract/tenant/renter-bill-preview-dialog.vue'
	import {defaultRenterContract, defaultRenterInfo, RenterContract, RenterContractDevice, RenterInfo} from '@/interface/contract'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import AccessAuthorizationDialog from '@/components/contract/add-tenant-contract-dialog/access-authorization-dialog.vue'
	import billApi from '@/api/bill-api'
	import {isLockinEnv} from 'yuxin-base/src/utils'
	import twoColumnsSelect from '@/components/common/two-columns-select.vue'
	import {discountTypeOptions} from '@/interface/interface'

	const store = useStore()

	const props = withDefaults(
		defineProps<{
			contract?: RenterContract
			id: string
			isShow?: boolean
		}>(),
		{
			contract: {
				// @ts-ignore成交方式【1-新签,2-续签,3-转租,4-换房】，默认新签
				signType: 1
			},
			id: ''
		}
	)

	const loadings = reactive({
		save: false,
		search: false
	})

	const disables = reactive({
		save: false
	})

	const visibles = reactive({
		footer: false,
		attachment: false,
		certificate: false,
		delivery: false,
		billPreview: false,
		accessAuth: false
	})

	// 合同类型
	const contractTypes = [
		{
			type: 2,
			title: '电子合同',
			subTitle: '需短信邀请租客完成线上签约',
			desc: '适用于新签租客，采用CA电子合同并实名认证租客身份，具备法律效力'
		},
		{
			type: 1,
			title: '纸质合同',
			desc: '适用于已签租客纸质合同，将合同信息补录到系统中，方便统一管理合同及收支账单'
		}
	]

	const emits = defineEmits(['update:visible', 'close', 'success'])
	const onCancel = () => {
		house.value = {}
		delivery.value = null
		templates.value = []
		attachments.value = []
		searchOption.options = []
		canceled.value = true
		contractId.value = ''
		XEUtils.assign(entity, defaultRenterContract())
		emits('update:visible', false)
		setTimeout(() => emits('close'), 100)
	}

	// 表单内容
	const form = ref<FormInstance>()
	// 租客信息
	const renter = ref<RenterInfo>({})
	// 物业交割单
	const delivery = ref<any>()
	// 合同附件
	const attachments = ref<Img[]>([])
	// 房源信息
	const house = ref<HouseDetail>({})
	// 合同信息
	const entity = reactive<RenterContract>(defaultRenterContract())
	// 租客原始信息
	const originRenterInfo = ref<RenterInfo>({})

	// 周期时长提示
	const cycleTip = ref<string>()

	//通行授权是否展示水电 续签则不展示
	const isShowHydropower = ref<boolean>(false)

	// 新增
	const enterPrise = reactive<any>({})
	/**
	 * 当前折扣比例
	 */
	const discountScale = ref<any>()

	/**
	 * 当前租金折扣类型 1每月折 2首月折 3尾月折
	 */
	const discountType = ref<any>()

	// 租客信息禁止编辑
	const renterDisabled = computed(() => house.value.status === 20 && house.value.houseBook !== null)

	// 爱好
	const hobbies = computed(() => {
		const interest = (entity.renterInfo || {}).interest || []
		return options.hobbies.filter((item: any) => interest.includes(item.id)).map((item: any) => item.name)
	})

	const disabledDate = (current: Dayjs) => {
		// 续、转、换合同开始时间禁用
		if ((entity.signType || 1) > 1) {
			return current.isBefore(entity.beginTime, 'day')
		} else {
			return false
		}
	}

	watchEffect(() => {
		// 计算合同周期月数
		if (entity.beginTime && entity.endTime) {
			cycleTip.value = ''
			const endTime = dayjs(entity.endTime).add(1, 'day')

			let years = endTime.diff(entity.beginTime, 'year', true)
			let months = endTime.diff(entity.beginTime, 'month', true)

			entity.leasePeriod = XEUtils.toInteger(months)
			if (years >= 1) {
				cycleTip.value = XEUtils.toInteger(years) + '年'
			}

			months = endTime.subtract(XEUtils.toInteger(years), 'year').diff(entity.beginTime, 'month', true)
			if (months >= 1) {
				cycleTip.value = (cycleTip.value || '') + XEUtils.toInteger(months) + '月'
			}

			const days = endTime.subtract(entity.leasePeriod, 'month').diff(entity.beginTime, 'day', true)
			if (days >= 1) {
				cycleTip.value = (cycleTip.value || '') + XEUtils.toInteger(days) + '天'
			}
		}
		// 附件列表
		entity.attachmentIds = attachments.value.map(o => o.id) as []
	})

	// 计算押金
	watch([() => entity.price, () => entity.depositMonth], () => {
		entity.deposit = XEUtils.multiply(entity.price, entity.depositMonth)
	})
	const canceled = ref(true)
	const contractId = ref('')
	const init = () => {
		if (canceled.value && props.contract?.signType === 2) {
			emits('update:visible', false)
			billApi.unclearedDeposit(props.contract?.contractId as string).then(({data = []}) => {
				if (data.length > 0) {
					message.error('原合同押金未结清，不能进行续租操作')
				} else {
					emits('update:visible', true)
					canceled.value = false
				}
			})

			return
		}

		getDics()
		const contract = props.contract || {}

		console.log('合同签约参数', toRaw(contract))

		let renterInfo = contract.renterInfo || {}

		if (contract.otherExpenses && XEUtils.isString(contract.otherExpenses)) {
			try {
				contract.otherExpenses = JSON.parse(contract.otherExpenses || '[]')
			} catch (e) {
				contract.otherExpenses = []
			}
		}

		// @ts-ignore，过滤掉空值
		renterInfo = XEUtils.pick(renterInfo, v => v)
		originRenterInfo.value = renterInfo

		delete contract.renterInfo
		console.log('租客信息=========>', renterInfo)

		if (XEUtils.isString(renterInfo.interest) && XEUtils.trim(renterInfo.interest)) {
			renterInfo.interest = renterInfo.interest.split('/')
		}

		XEUtils.merge(entity, defaultRenterContract(), contract, {
			renterInfo,
			contractId: null,
			contractNo: null,
			signEmpId: store.currentUser.empId,
			signDeptId: store.currentUser.deptId,
			signTime: nowDate()
		})

		// 续租、合同重置需要传contractId
		if (contract.contractId) {
			getContractDetail(contract.contractId)
			contractId.value = props.contract?.contractId || ''
		} else if (contract.houseId) {
			getHouseRoom(contract.houseId)
		}
		console.log('合同初始信息========>', toRaw(entity))
		console.log('oldDelivery===', contract.oldDelivery)
	}

	onMounted(() => {
		visibles.footer = true
		init()
		getData()
	})

	// 获取合同详情
	const getContractDetail = (id: string) => {
		getRenterContractDetail(id).then(({data}: {data: RenterContract}) => {
			const renterInfo = data.renterInfo || {}

			const signType = props.contract?.signType || 1

			if (signType > 1 && !entity.reset && !entity.resubmit) {
				data.contractId = null
				data.contractPid = id
				data.signType = signType
				data.signTime = nowDate()
				data.otherExpenses = []

				switch (signType) {
					case 2:
						// 续签周期计算
						data.beginTime = dayjs(data.endTime).add(1, 'day').format(DATE_FORMAT.DATE)
						if (props.contract?.endTime && props.contract.applyId) {
							data.endTime = props.contract.endTime
						} else {
							data.endTime = dayjs(data.beginTime).add(1, 'year').subtract(1, 'day').format(DATE_FORMAT.DATE)
						}
						break
					case 4:
						// 换房删除原房源id
						data.houseId = null
						// 换房周期计算，开始日期为操作日期第二天
						data.beginTime = dayjs(nowDate()).add(1, 'day').format(DATE_FORMAT.DATE)
						break
				}
			} else {
				entity.contractId = id

				if (XEUtils.isString(renterInfo.interest) && XEUtils.trim(renterInfo.interest)) {
					renterInfo.interest = renterInfo.interest.split('/')
				}

				if (data.otherExpenses && XEUtils.isString(data.otherExpenses)) {
					try {
						data.otherExpenses = JSON.parse(data.otherExpenses || '[]')
					} catch (e) {
						data.otherExpenses = []
					}
				}
			}

			// @ts-ignore
			data = XEUtils.pick(data, v => v)
			// @ts-ignore
			data.renterInfo = XEUtils.pick(renterInfo, v => v)

			XEUtils.merge(entity, data)

			delete entity.house

			console.log('合同详情==============>', toRaw(data))

			getHouseRoom(entity.houseId as string)
		})
	}
	// 查询房间是否绑定水电表
	const setEleAndWaterQuantity = () => {
		if (!deviceDetail.value.showWaterEle && !visibles.accessAuth) {
			updateClancel()
			return
		}
		getCurEleAndWaterQuantity({
			roomId: entity.houseId
		}).then((res: any) => {
			//绑定水电表切水电表为预付费
			if ((res.data.bindEleMater || res.data.bindClodWaterMater || res.data.bindHotWaterMater) && res.data.billGenerateMethod !== 3) {
				visibles.accessAuth = true
				isShowHydropower.value = true
			} else {
				isShowHydropower.value = false
			}
			if (!visibles.accessAuth) {
				updateClancel()
			}
		})
	}
	// 合同类型变更
	const onContractMediumChange = () => {
		form.value?.clearValidate()
		// 电子合同暂仅支持身份证
		if (entity.contractMedium === 2 && entity.renterInfo) {
			entity.renterInfo.certificationType = 1
		}
	}

	// 电子合同模板
	const templates = ref([])
	const templateOption = reactive({
		options: templates,
		size: 'small',
		bordered: false,
		showSearch: true,
		dropdownMatchSelectWidth: 300,
		optionFilterProp: 'contractTemplateName',
		placeholder: computed(() => (entity.houseId ? (templates.value.length ? '请选择模板' : '暂无电子合同模板') : '请先选择房源')),
		fieldNames: {label: 'contractTemplateName', value: 'id'}
	})

	// 房源搜索
	const searchOption = reactive<any>({
		options: [],
		allowClear: true,
		showSearch: true,
		optionFilterProp: 'address',
		placeholder: '请输入房源地址进行搜索',
		fieldNames: {label: 'address', value: 'houseRoomId'},
		style: {
			width: '100%'
		},
		onSearch(like: string) {
			if (like && like.trim()) {
				houseSearch(like)
			}
		},
		onSelect(value: string) {
			getHouseRoom(value)
			form.value?.clearValidate()
		},
		onDeselect() {
			templates.value = []
			entity.contractMedium = 1
			entity.econtractModelId = null
		}
	})

	const houseSearch = XEUtils.debounce((like: string) => {
		let params = {
			houseType: 0,
			like,
			current: 1,
			bizType: 1,
			size: 20,
			// hasHouseType: true,
			statusInCondition: [11]
		}

		// 签约未传入租客信息则搜索预定房源
		if (!originRenterInfo.value.name) {
			params.statusInCondition.push(20)
		}

		loadings.search = true
		houseApi
			.searchByAddress(params)
			.then((res: any) => {
				searchOption.options = res.data.records
			})
			.finally(() => (loadings.search = false))
	}, 300)

	// 当前签约房源
	const getHouseRoom = (id: string) => {
		entity.houseId = id
		houseApi.getHouseRoom(id).then(({data}: {data: HouseDetail}) => {
			console.log('房源详情==============>', toRaw(data))

			if (data.houseBook && data.houseBook.bookStatus === 1) {
				disables.save = true
				house.value = {}
				XEUtils.assign(entity, defaultRenterContract())

				return Modal.warning({
					centered: true,
					title: '系统提示',
					content: '当前房源存在预定未支付记录，请先完成支付或作废后再进行签约'
				})
			} else {
				disables.save = false
			}

			house.value = data

			entity.price = data.actualPrice
			entity.basePrice = data.basePrice
			entity.housePid = data.housePid
			entity.houseAddress = data.fullAddress
			entity.maintainerId = data.stewardId
			getTemplates(data.deptId as string)

			const signType = props.contract?.signType || 1

			// 有id代表是签约申请转签约、合同重置
			if (signType === 1 && !entity.id) {
				entity.leasePeriod = 12

				if (data.houseBookId && data.houseBook) {
					entity.renterInfo = defaultRenterInfo()

					const houseBook = data.houseBook
					entity.renterInfo.name = houseBook.name
					entity.renterInfo.phone = houseBook.phone
					entity.renterInfo.gender = houseBook.gender || 1
					entity.leasePeriod = houseBook.contractMonth
					entity.renterInfo.identityCard = houseBook.certificateNo
					entity.renterInfo.certificationType = houseBook.certificateType || 1

					quickSelectDate()
				}
			}

			if (searchOption.options.length === 0) {
				searchOption.options = [
					{
						housePid: entity.housePid,
						houseRoomId: entity.houseId,
						address: entity.houseAddress
					}
				]
			}
		})
	}

	// 根据房源部门获取电子合同模板
	const getTemplates = (deptId: string) => {
		entity.econtractModelId = null
		getContractTemplate({
			deptId,
			templateType: 1
		}).then(({data}) => {
			templates.value = data
			if (data && data.length) {
				entity.econtractModelId = data[0].id
			}
		})
	}

	const options = reactive<any>({
		// 客户来源
		sources: [],
		// 爱好
		hobbies: [],
		// 重点人群
		keyGroups: [],
		// 费用科目
		feeSubjects: [],
		// 证件类型
		certificateTypes: Object.keys(CERTIFICATION_TYPE_MAP).map(key => ({
			label: CERTIFICATION_TYPE_MAP[key],
			value: Number(key)
		})),
		// 企业列表
		enterpriseList: [],
		// 周期
		teamWork: [],
		// 折扣 协议
		discount: []
	})

	// 获取字典
	const getDics = () => {
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@HOBBY']).then(({data}) => (options.hobbies = data))
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@KEY_GROUPS']).then(({data}) => (options.keyGroups = data))
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@CHANNELSOURCE']).then(({data}) => (options.sources = data))
		settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT']).then(({data}) => (options.feeSubjects = data))

		getEnterPriseLibraryListAll({}).then(({data}) => {
			options.enterpriseList = data
			if (props.id) {
				enterpriseInformation(data)
			}
		})
	}

	// 房间编辑表格配置
	const togetherTable = ref<VxeTableInstance>()
	const togetherTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})

	// 其它费用
	const otherBillTable = ref<VxeTableInstance>()
	const otherBillTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})

	// 添加同住人
	const onClickToAddTogether = () => {
		entity.renterInfo?.togetherList?.push({
			gender: 1,
			certificationType: 1
		})

		togetherTable.value?.reloadData(entity.renterInfo?.togetherList as [])

		console.log(entity.renterInfo?.togetherList)
	}

	// 添加其它费用
	const onClickToAddOtherBill = () => {
		entity.otherExpenses?.push({})

		otherBillTable.value?.reloadData(entity.otherExpenses as [])

		console.log(entity.otherExpenses)
	}

	/** 加收费用 费用科目 change事件 */
	const feeSubjectChange = (value: string, row: any) => {
		let target: any = {}
		options.feeSubjects.forEach(item => {
			if (item.metaList.find(v => v.id === value)) {
				target = item
			}
		})
		if (target.label === 'FEESUBJECT@DEPOSIT') {
			console.log('付款方式 为 一次性付清 且 不可以修改')
			row.periodMonth = 99
			row.disabled = true
		} else {
			row.disabled = false
			if (row.periodMonth === 99) {
				delete row.periodMonth
			}
		}
	}

	const onClickToRemoveRow = (index: any, tableInstance: VxeTableInstance) => {
		Modal.confirm({
			title: '系统提示',
			content: '删除后无法恢复，确定删除？',
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			onOk() {
				tableInstance.data?.splice(index, 1)
				tableInstance.reloadData(tableInstance.data as [])
			}
		})
	}

	const onDateChange = (dates: string[]) => {
		dates = dates || []
		entity.beginTime = dates[0]
		entity.endTime = dates[1]
	}

	const quickSelectDate = () => {
		entity.beginTime = entity.beginTime || nowDate()
		entity.endTime = dayjs(entity.beginTime)
			.add(entity.leasePeriod || 12, 'month')
			.add(-1, 'day')
			.format(DATE_FORMAT.DATE)

		form.value?.validate('beginTime')
	}

	// 提交合同信息预览账单
	const submit = () => {
		form.value
			?.validate()
			.then(() => {
				visibles.billPreview = true
			})
			.catch(({errorFields}: any) => {
				form.value?.scrollToField(errorFields[0].name, {
					behavior: 'smooth'
				})
			})
	}

	// 合同签约成功
	const onSubmitSuccess = (id: string) => {
		saveDelivery(id)
		deviceAccessAuth(id)
	}
	const updateClancel = () => {
		let time = setTimeout(() => {
			onCancel()
			emits('success')
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
			clearTimeout(time)
		}, 50)
	}

	// 保存物业交割单
	const saveDelivery = (contractId: string) => {
		let deliverys: any = []

		if (props.contract?.oldDelivery) {
			deliverys.push(props.contract.oldDelivery)
		}

		if (!XEUtils.isEmpty(delivery.value)) {
			deliverys.push({
				...delivery.value,
				compactType: 1,
				deliveryType: 1,
				compactId: contractId,
				houseId: entity.houseId
			})
		}

		if (!XEUtils.isEmpty(deliverys)) {
			houseDeliveryBatchSave(deliverys)
				.then(({data}) => {
					console.log('物业交割单保存完毕========>', data)
				})
				.finally(() => (delivery.value = null))
		}
	}

	// 智能设备通行授权
	const deviceDetail = ref<RenterContractDevice>({} as RenterContractDevice)
	const deviceAccessAuth = (contractId: string) => {
		if (contractId) {
			let params = {
				id: contractId
			}
			renterContractDeviceDetail(params.id).then(({data}) => {
				data.renterInfos.forEach((item: any) => {
					item.accessAuthType = []
					item.lockAuthType = []
				})
				deviceDetail.value = data
				// showAccessLock 锁  showWaterEle 水电表 来自安全设置 是否展示
				if (!deviceDetail.value.showAccessLock && props.contract?.signType === 2) {
					updateClancel()
					return
				} else if (!deviceDetail.value.showAccessLock && props.contract?.signType !== 2) {
					setEleAndWaterQuantity()
					return
				}
				if (deviceDetail.value.hasLock || deviceDetail.value.hasAccess) {
					visibles.accessAuth = true
				} else {
					updateClancel()
				}

				// 续签不展示水电
				if (props.contract?.signType === 2) {
					if (!visibles.accessAuth) {
						updateClancel()
					}
					return
				} else {
					//云丁环境判断是否绑定水电表
					if (isLockinEnv()) {
						setEleAndWaterQuantity()
					}
				}
			})
		}
	}
	let needPhoto = ref(true)
	// 获取设置中是否控制租客端身份认证必填
	const getData = () => {
		let params = {
			bizPoint: 'TENANTSIDE_SETTING',
			module: 'TENANTSIDE'
		}
		settingApi.getDecisionList(params).then(res => {
			if (!Array.isArray(res.data)) return
			const data2 = res.data.find(v => v.mark === 'TENANTSIDE_SIGN_UPLOAD_IDCARD_SETTING')
			// entity.renterInfo.needPhoto = JSON.parse(data2?.value).includes(1)
			// console.log(1096, needPhoto)
			// console.log(1099, entity.renterInfo)
		})
	}

	// 选择企业
	const selectEnterPriseId = (value: any) => {
		let arr = options.enterpriseList.filter(e => e.id === value)[0]
		XEUtils.assign(enterPrise, arr)
		// 回显各个字段
		entity.societyCode = enterPrise.societyCode
		entity.linkmanName = enterPrise.linkmanName
		entity.linkmanPhone = enterPrise.linkmanPhone
		entity.renterInfo.name = enterPrise.linkmanName
		entity.renterInfo.phone = enterPrise.linkmanPhone
		entity.renterInfo.identityCard = enterPrise.linkmanIdCard
		entity.renterInfo.employer = enterPrise.enterPriseName

		options.teamWork = enterPrise.teamworks?.map((e: any) => {
			return {
				...e,
				period: e.beginTime.substr(0, 10) + '至' + e.endTime.substr(0, 10)
			}
		})

		// options回显name重构
		options.discount = enterPrise.teamworks?.map((i: any) => {
			let from = i.discounts?.map((e: any) => {
				let name =
					e.enterPriseTeamWordDetailsName +
					'/' +
					(e.type === 1 ? '折扣' : '') +
					'/' +
					discountTypeOptions.filter(j => j.value === e.discountType)[0]?.label +
					'/' +
					e.discountScale +
					'%'
				return {
					...e,
					name: name
				}
			})

			return {
				...i,
				discounts: from
			}
		})
		// 过滤出最优折扣id所在数组
		options.discount = options.discount?.filter((e: any) => {
			return e.discounts?.some((j: any) => j.id === enterPrise.enterPriseTeamWorkDicCountId)
		})[0].discounts

		// 折扣id和周期id 最优在最外层
		entity.enterPriseTeamWorkId = enterPrise.enterPriseTeamWorkId
		entity.enterPriseTeamworkDiscountId = enterPrise.enterPriseTeamWorkDicCountId

		discountScale.value = enterPrise.discountScale
		discountType.value = enterPrise.discountType
		checkData()
	}

	// 获取企业信息详情
	const enterpriseInformation = (data: any) => {
		const res = data.find((e: any) => e.id === props.id)
		// console.log(res)
		// enterpriseDetails(props.id as string).then(res => {
		// enterpriseId.value = res.id
		// record.enterpriseData = res.data
		entity.enterPriseId = res.id
		entity.societyCode = res.societyCode
		entity.linkmanName = res.linkmanName
		entity.linkmanPhone = res.linkmanPhone
		entity.renterInfo.name = res.linkmanName
		entity.renterInfo.phone = res.linkmanPhone
		entity.renterInfo.identityCard = res.linkmanIdCard
		entity.renterInfo.employer = res.enterPriseName
		options.teamWork = res.teamworks?.map((e: any) => {
			return {
				...e,
				period: e.beginTime + '至' + e.endTime
			}
		})
		entity.enterPriseTeamWorkId = options.teamWork[0].id

		options.discount = res.teamworks?.map((i: any) => {
			let from = i.discounts?.map((e: any) => {
				let name =
					e.enterPriseTeamWordDetailsName +
					'/' +
					(e.type === 1 ? '折扣' : '') +
					'/' +
					discountTypeOptions.filter(j => j.value === e.discountType)[0]?.label +
					'/' +
					e.discountScale +
					'%'
				return {
					...e,
					name: name
				}
			})

			return {
				...i,
				discounts: from
			}
		})
		options.discount = options.discount?.filter((e: any) => {
			return e.discounts?.some((j: any) => j.id === res.enterPriseTeamWorkDicCountId)
		})[0].discounts

		// 折扣id和周期id 最优在最外层
		entity.enterPriseTeamWorkId = res.enterPriseTeamWorkId
		entity.enterPriseTeamworkDiscountId = res.enterPriseTeamWorkDicCountId

		discountScale.value = res.discountScale
		discountType.value = res.discountType
		// })
	}

	/**
	 * 合作周期是否和合同周期冲突
	 */
	const checkData = () => {
		let beginTime = options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0]?.beginTime
		let endTime = options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0]?.endTime
		if (
			(entity.beginTime as string) < beginTime ||
			(entity.beginTime as string) > endTime ||
			(entity.endTime as string) < beginTime ||
			(entity.endTime as string) > endTime
		) {
			entity.beginTime = null
			entity.endTime = null
			entity.leasePeriod = null
		}
	}

	const selectWorkId = (value: any) => {
		let arr = enterPrise.teamworks.filter(e => e.id === value)[0]
		options.discount = arr?.discounts?.map((e: any) => {
			return {
				...e,
				name: e.enterPriseTeamWordDetailsName + '/' + e.discountScale + '%'
			}
		})
		entity.enterPriseTeamworkDiscountId = options.discount[0]?.id
		// 折扣默认选择第一个
		discountScale.value = options.discount[0]?.discountScale
		discountType.value = options.discount[0]?.discountType

		onSubmitF()
		checkData()
	}

	// 选择房间回显 and 周期 折扣 租金 押金
	const onSubmitF = (data?: any) => {
		if (data) {
			entity.enterPriseContractHouseRoomFroms = data
		}

		entity.price = 0
		entity.deposit = 0
		entity.enterPriseContractHouseRoomFroms?.forEach((e: any) => {
			// 新增一个计算价格 后面账单预览使用
			e.countPprice = discountType.value === 1 ? Number(((e.price * Number(discountScale.value)) / 100).toFixed(2)) : e.price
			e.countDeposit = discountType.value === 1 ? Number(((e.deposit * Number(discountScale.value)) / 100).toFixed(2)) : e.deposit

			entity.price += e.countPprice
			entity.deposit += e.countDeposit
		})

		entity.price = Number(entity.price.toFixed(2))
		entity.deposit = Number(entity.deposit.toFixed(2))
	}

	const selectDiscountId = (value: any) => {
		options.teamWork.forEach((e: any) => {
			e.discounts.forEach(j => {
				if (j.id === value) {
					discountScale.value = j.discountScale
					discountType.value = j.discountType
				}
			})
		})

		onSubmitF()
	}
</script>

<style lang="less">
	.renter-sign-dialog {
		.ant-form-item {
			margin-bottom: 16px;

			label[for='form_item_beginTime'] {
				display: flex;

				.display-flex {
					flex: 1;
					justify-content: space-around;
				}
			}
		}

		.custom-radio-group {
			.ant-space {
				display: flex;

				.ant-space-item {
					flex: 1;
				}
			}

			.ant-radio-button-wrapper {
				height: 96px;
				display: block;

				.ant-typography {
					margin-bottom: 6px;
				}
			}
		}

		.template-select-wrapper {
			.ant-form-item-control {
				flex-direction: row;
				align-items: center;
				gap: 16px;

				.ant-select-selection-search {
					left: 0;
				}

				.ant-form-item-extra {
					color: @warning-color;
					font-size: @font-size-sm;
				}
			}

			.ant-select {
				width: 160px;

				.ant-select-selector {
					padding: 0;
					font-size: @font-size-sm;
				}
			}
		}

		.month-quick-radio-group {
			.ant-radio-button-wrapper {
				padding: 0 9px;
			}
		}

		.ant-input-number-group-addon {
			background: #fff;
			color: @text-color;
		}

		.edit-table-row {
			.ant-input,
			.ant-select-selector {
				padding: 0;
				border: none;
			}

			.ant-select,
			.ant-input-number {
				width: 100%;
			}

			.ant-radio-wrapper:last-child {
				margin-right: 0;
			}
		}
	}
</style>
